import React, {useEffect, useState} from 'react';
import {IconButton} from "./button";
import {Modal} from "@/app/components/ui-lib";

const styles = {
    button: {
        fontSize: '12px',
        textDecoration: 'none',
        textAlign: 'center' as any,
        background: 'var(--primary)',
        color: '#FFF',
        display: 'block',
        lineHeight: '20px',
        padding: '0 5px',
        borderRadius: '8px',
        marginRight: '5px',
        flex: 1,
    }
};

export function FocusAnyBox() {

    const [user, setUser] = useState({
        isLogin: false,
        avatar: 'https://cdn.focusany.com/asset/image/avatar.svg',
        nickname: '未登录'
    })
    const [showChargeModel, setShowChargeModel] = useState(false);
    const [quota, setQuota] = useState('加载中...');
    const [goodsList, setGoodsList] = useState([
        // {
        //     "id": "1739261943214012682",
        //     "title": "AI聊天充值1000万",
        //     "cover": "https://ms-assets.modstart.com/data/image/2025/02/11/29908_cdxd_4280.png",
        //     "priceType": "fixed",
        //     "fixedPrice": "189.99",
        //     "description": "充值1000万Token"
        // },
        // {
        //     "id": "1739257308395964590",
        //     "title": "AI聊天充值100万",
        //     "cover": "https://ms-assets.modstart.com/data/image/2025/02/11/29908_cdxd_4280.png",
        //     "priceType": "fixed",
        //     "fixedPrice": "19.90",
        //     "description": "充值100万Token"
        // }
    ] as {
        id: string,
        title: string,
        cover: string,
        priceType: string,
        fixedPrice: string,
        description: string,
    }[]);

    const formatQuota = (quota: number) => {
        if (quota < 10000) {
            return quota;
        } else if (quota < 1000000) {
            return (quota / 10000).toFixed(2) + '万';
        } else {
            return (quota / 1000000).toFixed(2) + '百万';
        }
    }

    const doLogin = async () => {
        try {
            // @ts-ignore
            await window.focusany.showUserLogin()
        } catch (e) {
            console.error('doLogin', e);
        }
    }

    const doLoadGoods = async () => {
        try {
            // @ts-ignore
            let list = await window.focusany.listGoods()
            // 根据价格排序
            list = list.sort((a: any, b: any) => {
                return a.fixedPrice - b.fixedPrice
            })
            // @ts-ignore
            setGoodsList(list)
        } catch (e) {
        }
    }

    const doRefresh = async () => {
        try {
            // @ts-ignore
            const userCurrent = window.focusany.getUser()
            const userNew = {
                // @ts-ignore
                isLogin: userCurrent?.isLogin,
                avatar: userCurrent?.avatar,
                nickname: userCurrent?.nickname
            }
            setQuota('加载中...');
            // @ts-ignore
            const res = await window.focusany.apiPost('plugin/Chat/info', {})
            console.log('info', res);
            if (res.code) {
                if (res.code === 1001) {
                    userNew.isLogin = false;
                    setQuota('-');
                } else {
                    setQuota('加载失败');
                }
            } else {
                userNew.isLogin = true;
                // @ts-ignore
                setQuota(formatQuota(res.data.quota as number));
                // @ts-ignore
                window.__FocusAnyApiKey = res.data.apiKey;
            }
            setUser(userNew as any);
        } catch (e) {
            console.error('doRefresh', e);
            setQuota('加载失败');
        }
    }

    const doCharge = async (goodsId: string) => {
        let result = await window.focusany.openGoodsPayment({
            goodsId: goodsId
        })
        if (result.paySuccess) {
            doRefresh();
            setShowChargeModel(false);
        }
    }

    // @ts-ignore
    focusany.offPluginEventAll('UserChange');
    // @ts-ignore
    focusany.onPluginEvent('UserChange', (data: any) => {
        doRefresh();
    })

    useEffect(() => {
        doRefresh();
    }, []);

    return (
        <div style={{
            paddingBottom: "10px",
            fontSize: "12px",
        }}>
            <div style={{
                display: "flex",
                alignItems: "center",
            }}>
                <div style={{
                    marginRight: "10px",
                }}>
                    <img src={user.avatar} alt="avatar" style={{
                        width: "30px",
                        height: "30px",
                        borderRadius: "50%",
                        border: "1px solid #CCC",
                        cursor: "pointer",
                    }}/>
                </div>
                <div style={{
                    flex: 1,
                }}>
                    <div style={{
                        fontWeight: "bold",
                        marginBottom: "5px",
                    }}>
                        {user.isLogin ? user.nickname : '未登录'}
                    </div>
                    {
                        user.isLogin && <div>
                            Token剩余:{quota}
                        </div>
                    }
                </div>
            </div>
            <div style={{
                marginTop: "10px",
                display: "flex"
            }}>
                <a href="javascript:;" onClick={doRefresh} style={styles.button}>
                    刷新
                </a>
                {
                    !user.isLogin && <a href="javascript:;" onClick={doLogin} style={styles.button}>
                        登录
                    </a>
                }
                {
                    user.isLogin && <a href="javascript:;" onClick={() => {
                        setShowChargeModel(true);
                        doLoadGoods()
                    }} style={styles.button}>
                        充值
                    </a>
                }
            </div>
            {showChargeModel &&
                <div className="modal-mask">
                    <Modal
                        title="Token充值"
                        onClose={() => {
                            setShowChargeModel(false);
                        }}>
                        <div style={{
                            display: "flex",
                        }}>
                            {goodsList.map((goods) => (
                                <div key={goods.id} style={{
                                    flex: 1,
                                    padding: "10px",
                                    border: "1px solid #f1f5f9",
                                    borderRadius: "5px",
                                    margin: "5px",
                                    textAlign: "center",
                                }}>
                                    <div style={{
                                        fontSize: "20px",
                                        marginBottom: "10px",
                                    }}>{goods.title}</div>
                                    <div style={{
                                        fontSize: "14px",
                                        height: "14px",
                                        lineHeight: "14px",
                                        overflow: "hidden",
                                        marginBottom: "10px",
                                    }}>{goods.description}</div>
                                    <div style={{
                                        fontSize: "18px",
                                        color: "#f00",
                                        marginBottom: "10px",
                                    }}>¥{goods.fixedPrice}</div>
                                    <div style={{
                                        textAlign: "center",
                                    }}>
                                        <IconButton
                                            style={{
                                                margin: "0 auto"
                                            }}
                                            text="支付充值"
                                            onClick={() => {
                                                doCharge(goods.id);
                                            }}
                                            type="primary"
                                        />
                                    </div>
                                </div>
                            ))}
                        </div>
                    </Modal>
                </div>}
        </div>
    );
}
